package com.example.mail;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import com.example.R;
import com.example.popup.Alert;
import core.communication.ServerConnectorManager;
import core.exception.BaseException;
import core.model.Game;
import core.model.mail.Message;

import java.util.ArrayList;

import static core.model.mail.Message.MessageType.BROADCAST;
import static core.model.mail.Message.MessageType.PRIVATE;


public class MailTypeActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mailtypelayout);

        Game game = (Game) getIntent().getExtras().getSerializable("game");

        final ServerConnectorManager connector = new ServerConnectorManager(game);
        core.model.mail.Context preContext;
        try {
            preContext = connector.loadMessages();
        } catch (BaseException e) {
            preContext = new core.model.mail.Context();
            Alert.error(this, e);
        }

        final core.model.mail.Context context = preContext;

        TextView broadcastButton = (TextView) findViewById(R.id.showBroadcastsButton);

        broadcastButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                showMessageList(BROADCAST, context);
            }
        });


        TextView privateButton = (TextView) findViewById(R.id.showPrivatesButton);

        privateButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                showMessageList(PRIVATE, context);
            }
        });

    }

    private void showMessageList(Message.MessageType messageType, core.model.mail.Context context) {
        View view = findViewById(R.id.mailTypes);
        Context viewContext = view.getContext();

        Intent i = new Intent(viewContext, MailListActivity.class);

        switch (messageType) {
            case PRIVATE:
                // todo "messages" should constant
                i.putExtra("messages", (ArrayList<Message>) context.getPrivates());
                break;

            case BROADCAST:
                // todo "messages" should constant
                i.putExtra("messages", (ArrayList<Message>) context.getBroadcasts());
                break;
        }


        viewContext.startActivity(i);
    }
}
